package com.p2p.base.util.sms;

import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.commons.codec.binary.Base64;

public class LuoSiMaoSMSDemo2 {

	private static final String key = "1dc74e82085555d13a308fas8da8da";

	public static void main(String args[]) {
		try {
			testSend("18971326300");
			// System.out.print(testStatus());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private static void testSend(String tel) throws Exception {
		String url = "http://sms-api.luosimao.com/v1/send.json";
		CloseableHttpClient hc = HttpClients.createDefault();
		HttpPost post = new HttpPost(url);
		post.addHeader(
				"Authorization",
				"Basic "
						+ new Base64().encodeToString(("api:key-"
								+ "1dc74e82085555d13a3042d5ga32fdc5f")
								.getBytes("utf-8")));
		ArrayList nvps = new ArrayList();
		nvps.add(new BasicNameValuePair("mobile", tel));
		nvps.add(new BasicNameValuePair("message", "测试内容【某某公司】"));
		post.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
		CloseableHttpResponse resp = hc.execute(post);
		if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			HttpEntity entity = resp.getEntity();
			String r = EntityUtils.toString(entity, "utf8");
			EntityUtils.consume(entity);
			if (r.indexOf("ok") == -1) {
				throw new Exception("发送短信异常：" + tel + "#" + r);
			}
		} else {
			throw new Exception("发送短信异常："
					+ resp.getStatusLine().getStatusCode());
		}
	}

	private static String testStatus() throws Exception {
		String url = "http://sms-api.luosimao.com/v1/status.xml";
		CloseableHttpClient hc = HttpClients.createDefault();
		HttpPost post = new HttpPost(url);
		post.addHeader(
				"Authorization",
				"Basic "
						+ new Base64().encodeToString(("api:"
								+ key)
								.getBytes("utf-8")));
		CloseableHttpResponse resp = hc.execute(post);
		if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			HttpEntity entity = resp.getEntity();
			String r = EntityUtils.toString(entity, "utf8");
			EntityUtils.consume(entity);
			if (r.indexOf("0") == -1) {
				throw new Exception("查询状态异常：" + r);
			} else {
				return r;
			}
		} else {
			throw new Exception("查询状态异常："
					+ resp.getStatusLine().getStatusCode());
		}
	}
}